<template>
    <div>
        <a-select
            label-in-value
            :value="customerNumber"
            placeholder="选择生产单位"
            style="width: 100%"
            :filter-option="false"
            :not-found-content="fetching ? undefined : null"
            show-search
            @search="fetchUser"
            @change="handleChange"
        >
            <a-spin v-if="fetching" slot="notFoundContent" size="small"/>
            <a-select-option value="">全部</a-select-option>
            <a-select-option v-for="d in data" :key="d.value">
                {{ d.label }}
            </a-select-option>
        </a-select>
    </div>
</template>

<script>
import { getCustomerListByName } from '../../api/customer'
export default {
    name: 'SelectCustomerList',
    props:{
        customerNumbers : {
            type : String,
            default : ''
        }
    },
    data() {
        this.lastFetchId = 0;
        return {
            data: [],
            customerNumber : '',
            fetching: false
        }
    },
    watch:{
        customerNumbers(){
            this.customerNumber = this.customerNumbers;
            console.log('customerNumber',this.customerNumber);
        }
    },
    methods: {
        // 清空选择的区域
        clearSelectCustomer(){
            this.customerNumber = '';
        },
        async fetchUser(value) {
            console.log('fetching user', value)
            this.lastFetchId += 1
            const fetchId = this.lastFetchId
            this.data = []
            this.fetching = true
            let params = {
                customerName: value
            }
            // 根据当前用户去查询
            let userInfo = this.$store.getters.userInfo;
            if(userInfo.cityCode){
                params.cityCode = userInfo.cityCode;
            }
            if(userInfo.areaCode){
                params.areaCode = userInfo.areaCode;
            }
            if(userInfo.companysId){
                params.companysId = userInfo.companysId;
            }

            let list = await getCustomerListByName(params);
            if (fetchId !== this.lastFetchId) {
                return
            }
            const data = list.map(item => ({
                label: item.customerName,
                value: item.customerNumber
            }))
            this.data = data;
            this.fetching = false;
        },
        filterOption: function(input, option) {
            return (
                option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
            )
        },
        handleChange: function(input, option) {
            let value = input.key || '';
            let label = (input.label || '').trim();
            this.customerNumber = input;
            this.$emit('change', value, label,option)
        }
    }
}
</script>

<style scoped>

</style>
